package com.example.words;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

//singleton 只生成一个实例
@Database(entities = {Word.class},version = 5,exportSchema = false)
public abstract class WordDataBase extends RoomDatabase {
    private static WordDataBase INSTANCE;
    static synchronized WordDataBase getDatabase(Context context){
        if(INSTANCE ==null){
            INSTANCE = Room.databaseBuilder(context.getApplicationContext(),WordDataBase.class,"word_data_base")
//                    .fallbackToDestructiveMigration()
                    .addMigrations(MIGRATOR_4_5)
                    .build();
        }
        return  INSTANCE;
    }
    public abstract WordDao getWordDao();


    //新增键
    static  final Migration MIGRATOR_2_3 = new Migration(2, 3) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("ALTER TABLE word ADD COLUMN bar_data INTEGER NOT NULL DEFAULT 1");
        }
    };

    //删除键
    static  final Migration MIGRATOR_3_4 = new Migration(3, 4) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //创建新的表
            database.execSQL("CREATE TABLE word_temp (id INTEGER PRIMARY KEY NOT NULL,english_word TEXT," +
                    "chinese_meaning TEXT)");
            //复制旧的表
            database.execSQL("INSERT INTO word_temp (id,english_word,chinese_meaning)" +
                    "SELECT id,english_word,chinese_meaning FROM word");
            //删除旧表格
            database.execSQL("DROP TABLE word");
            //加入新表格
            database.execSQL("ALTER TABLE word_temp RENAME to word");

        }
    };

    //业务 增加
    static  final Migration MIGRATOR_4_5 = new Migration(4, 5) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("ALTER TABLE word ADD COLUMN chinese_invisible INTEGER NOT NULL DEFAULT 0");
        }
    };

}
